
// https://leetcode.cn/problems/pacific-atlantic-water-flow/description/

class Solution
{
    int m, n;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };

public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights)
    {
        m = heights.size();
        n = heights[0].size();
        vector<vector<int>> pac(m, vector<int>(n, 0));
        vector<vector<int>> atl(m, vector<int>(n, 0));

        for (int i = 0; i < n; ++i)
        {
            if (pac[0][i] == 0)
                dfs(heights, 0, i, pac);
            if (atl[m - 1][i] == 0)
                dfs(heights, m - 1, i, atl);
        }
        for (int i = 0; i < m; ++i)
        {
            if (pac[i][0] == 0)
                dfs(heights, i, 0, pac);
            if (atl[i][n - 1] == 0)
                dfs(heights, i, n - 1, atl);
        }

        vector<vector<int>> res;
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
            {
                if (pac[i][j] && atl[i][j])
                {
                    res.push_back({ i, j });
                }
            }

        return res;
    }

    void dfs(vector<vector<int>>& heights, int i, int j, vector<vector<int>>& water)
    {
        water[i][j] = 1;
        for (int k = 0; k < 4; ++k)
        {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && water[x][y] != 1 && heights[x][y] >= heights[i][j])
            {
                dfs(heights, x, y, water);
            }
        }
    }
};